<template>
  <XenPageLayout
    title="应聘申请详情"
    title-align="left"
    navbar-bg-color="#7881de"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    contentStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;"
    :loading="loading"
    :error="hasError"
    @retry="loadInterviewDetail(Id)"
  >
    <!-- 主要内容区域 -->
    <view class="main-content" :class="{ 'has-audit-actions': isMyApprove }">
      <!-- 标签按钮网格 -->
      <view class="tab-grid">
        <view
          v-for="(tab, index) in tabs"
          :key="index"
          class="tab-button"
          :class="{ active: currentTab === index }"
          @click="switchTab(index)"
          @touchstart="() => {}"
        >
          <text class="tab-label">{{ tab.title }}</text>
        </view>
      </view>

      <!-- 标签内容区域 -->
      <view class="tab-content-wrapper">
        <!-- 基本信息 -->
        <view v-if="currentTab === 0" class="tab-content">
          <view class="details-card">
            <view class="card-content">
              <!-- 使用动态详情组件 -->
              <XenDynamicDetailsCard
                :sections="formSections as any"
                :data="originalData"
                :field-mapping="fieldMapping"
                :get-image-url="getImageUrl"
                @preview-image="previewImage"
              />

              <!-- 审核时间线组件 - 所有用户都有权限查看 -->
              <XenAuditTimeline :steps="timelineData" />
            </view>
          </view>
        </view>

        <!-- 学习经历 -->
        <view v-if="currentTab === 1" class="tab-content">
          <view class="subtable-card">
            <view class="card-header">
              <text class="card-title">学习经历信息</text>
              <text class="card-subtitle">学校、专业、学历等教育背景信息</text>
            </view>
            <view class="card-content">
              <DetailEducationInfo :person-id="Id" :readonly="true" />
            </view>
          </view>
        </view>

        <!-- 家庭成员 -->
        <view v-if="currentTab === 2" class="tab-content">
          <view class="subtable-card">
            <view class="card-header">
              <text class="card-title">家庭成员信息</text>
              <text class="card-subtitle"
                >家属姓名、关系等家庭成员详细信息</text
              >
            </view>
            <view class="card-content">
              <DetailFamilyInfo :person-id="Id" :readonly="true" />
            </view>
          </view>
        </view>

        <!-- 工作经历 -->
        <view v-if="currentTab === 3" class="tab-content">
          <view class="subtable-card">
            <view class="card-header">
              <text class="card-title">工作经历信息</text>
              <text class="card-subtitle"
                >以往工作单位、岗位、时间等工作经历</text
              >
            </view>
            <view class="card-content">
              <DetailWorkInfo :person-id="Id" :readonly="true" />
            </view>
          </view>
        </view>

        <!-- 荣誉职称 -->
        <view v-if="currentTab === 4" class="tab-content">
          <view class="subtable-card">
            <view class="card-header">
              <text class="card-title">荣誉职称信息</text>
              <text class="card-subtitle"
                >资质证书、职称等级、荣誉奖项信息</text
              >
            </view>
            <view class="card-content">
              <DetailHonorInfo :person-id="Id" :readonly="true" />
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 审核操作按钮组件 - 根据IsMyApprove字段控制显示 -->
    <XenAuditActions
      v-if="isMyApprove"
      ref="auditActionsRef"
      :actions="auditActions"
      @action="handleAuditAction"
    />
  </XenPageLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { onLoad, onShareAppMessage } from "@dcloudio/uni-app";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import XenDynamicDetailsCard from "@/components/XenDynamicDetailsCard.vue";
import XenAuditTimeline from "@/components/XenAuditTimeline.vue";
import XenAuditActions from "@/components/XenAuditActions.vue";
import { getFormSectionsByPageType } from "./form-config";
import { useInterviewInfo } from "./composables/useInfo";
// 导入详情页子表组件
import DetailEducationInfo from "./components/DetailEducationInfo.vue";
import DetailFamilyInfo from "./components/DetailFamilyInfo.vue";
import DetailWorkInfo from "./components/DetailWorkInfo.vue";
import DetailHonorInfo from "./components/DetailHonorInfo.vue";

import commonApi from "@/api/common";
import SysHrInterviewRequestBillApi from "./api/index";
import type { QueryTimeline, WorkflowInfo } from "@/type/common";
import type { ISysHrInterviewRequestBillVm } from "./api/interface";

// 获取详情页面的表单分组配置
const formSections = computed(() => getFormSectionsByPageType("details"));

// 页面状态
const Id = ref<string>("");
const hasError = ref<boolean>(false);

// 当前标签页
const currentTab = ref(0);

// 标签页配置
const tabs = ref([
  {
    title: "基本信息",
  },
  {
    title: "学习经历",
  },
  {
    title: "家庭成员",
  },
  {
    title: "工作经历",
  },
  {
    title: "荣誉职称",
  },
]);

// 切换标签页
const switchTab = (index: number) => {
  currentTab.value = index;
};

// 审核相关数据
const timelineData = ref<WorkflowInfo[]>([]);
const isMyApprove = ref<boolean>(false);
const auditLoading = ref<boolean>(false);
const auditActionsRef = ref();

// 创建API实例
const commonApiInstance = commonApi();
const api = SysHrInterviewRequestBillApi();

// 使用应聘申请信息 Composable
const {
  loading,
  originalData,
  getImageUrl,
  initializeOptions,
  loadInterviewDetail,
  fieldMapping,
} = useInterviewInfo();

// 招聘发布单信息
const recruitPublishInfo = ref<string>("");

// 获取招聘发布单详细信息
const loadRecruitPublishInfo = async () => {
  if (!originalData.value?.RecruitPublishRequestBillId) {
    return;
  }

  try {
    // 使用搜索API获取招聘发布单信息
    const searchResponse = await api.searchRecruitPublishRequestBills({
      // 搜索所有招聘发布单
    });

    if (searchResponse.Code === 200 && searchResponse.Data) {
      // 查找匹配的招聘发布单
      const matchedBill = searchResponse.Data.find((bill: any) => {
        return bill.ID === originalData.value.RecruitPublishRequestBillId;
      });

      if (matchedBill) {
        // 设置显示文本：岗位标题 (单据编号)
        const displayText = `${matchedBill.Title} (${matchedBill.BillCode})`;
        recruitPublishInfo.value = displayText;

        // 直接修改原始数据中的招聘发布单字段，让组件显示文字而不是ID
        if (originalData.value) {
          originalData.value.RecruitPublishRequestBillId = displayText;
        }
      } else {
        recruitPublishInfo.value =
          originalData.value.RecruitPublishRequestBillId || "";
      }
    } else {
      recruitPublishInfo.value =
        originalData.value.RecruitPublishRequestBillId || "";
    }
  } catch (error) {
    console.error("获取招聘发布单信息失败:", error);
    recruitPublishInfo.value =
      originalData.value.RecruitPublishRequestBillId || "";
  }
};

// 审核操作按钮配置
const auditActions = computed(() => [
  {
    key: "approve",
    label: "同意",
    type: "primary" as const,
    icon: "checkmarkempty",
    primary: true,
    customStyle: "background: #409eff; color: #ffffff;",
    disabled: auditLoading.value,
  },
  {
    key: "reject",
    label: "拒绝",
    type: "danger" as const,
    icon: "closeempty",
    primary: true,
    customStyle: "background: #f56c6c; color: #ffffff;",
    disabled: auditLoading.value,
  },
]);

// 获取时间线数据
const getTimelineData = async () => {
  if (!Id.value) return;

  try {
    const params: QueryTimeline = {
      entityId: Id.value,
      entitytype: "HengTong.Model.Db.Bill.SysHrInterviewRequestBill",
    };

    const response = await commonApiInstance.getTimeline(params);
    timelineData.value = response || [];
  } catch (error) {
    console.error("获取时间线数据失败:", error);
    timelineData.value = [];
  }
};

// 处理审核操作
const handleAuditAction = (action: any, remark?: string) => {
  console.log("审核操作:", action, "审批原因:", remark);

  switch (action.key) {
    case "approve":
      handleApprove(remark);
      break;
    case "reject":
      handleReject(remark);
      break;
    default:
      console.log("未知操作:", action.key);
  }
};

// 审核通过
const handleApprove = (remark?: string) => {
  // 直接执行同意操作，因为审批原因已经在组件中收集
  performAudit("同意", remark);
};

// 审核拒绝
const handleReject = (remark?: string) => {
  // 直接执行拒绝操作，因为拒绝原因已经在组件中收集
  performAudit("拒绝", remark);
};

// 执行审核操作
const performAudit = async (actionName: string, remark?: string) => {
  if (!originalData.value) {
    uni.showToast({
      title: "数据异常，请刷新页面重试",
      icon: "none",
    });
    return;
  }

  auditLoading.value = true;

  try {
    // 构造请求参数
    const requestData: ISysHrInterviewRequestBillVm = {
      ActionName: actionName,
      Entity: originalData.value,
      IsMyApprove: isMyApprove.value,
      Remark: remark || null, // 添加拒绝原因
    };

    // 调用审核接口
    const result = await api.approve(requestData);

    if (result) {
      // 关闭审批弹窗（同意和拒绝操作都需要关闭）
      if (actionName === "拒绝" || actionName === "同意") {
        auditActionsRef.value?.closeRejectPopup();
      }

      uni.showToast({
        title: `${actionName}成功`,
        icon: "success",
      });

      // 延迟1秒后返回页面
      setTimeout(() => {
        uni.navigateBack({
          success: () => {
            console.log("返回页面成功");
          },
          fail: () => {
            console.log("返回页面失败，尝试跳转到工作台");
            uni.reLaunch({
              url: "/pages/work/work",
              fail: () => {
                console.log("跳转工作台失败");
              },
            });
          },
        });
      }, 1000);
    }
  } catch (error) {
    console.error("审核操作失败:", error);

    // 处理不同类型的错误
    let errorMessage = "审核操作失败";
    if (error && typeof error === "object") {
      if ("message" in error && typeof error.message === "string") {
        errorMessage = error.message;
      } else if (
        "data" in error &&
        error.data &&
        typeof error.data === "object" &&
        "message" in error.data
      ) {
        errorMessage = error.data.message as string;
      }
    }

    uni.showToast({
      title: errorMessage,
      icon: "none",
      duration: 3000,
    });
  } finally {
    auditLoading.value = false;
  }
};

// 预览图片 - 统一的图片预览函数
const previewImage = (fileId: string | null) => {
  if (!fileId) {
    uni.showToast({
      title: "图片无效",
      icon: "none",
    });
    return;
  }

  const imageUrl = getImageUrl(fileId);
  if (!imageUrl) {
    uni.showToast({
      title: "图片无效",
      icon: "none",
    });
    return;
  }

  uni.previewImage({
    urls: [imageUrl],
    current: imageUrl,
    fail: () => {
      uni.showToast({
        title: "预览图片失败",
        icon: "none",
      });
    },
  });
};

// 获取分享标题
const getShareTitle = () => {
  if (originalData.value?.BillCode) {
    return `应聘申请${originalData.value.BillCode}`;
  }
  return "应聘申请详情";
};

// 获取分享路径
const getSharePath = () => {
  if (Id.value) {
    return `/subpkg-hr-syshrinterviewrequestbill/detail?id=${Id.value}`;
  }
  return "/subpkg-hr-syshrinterviewrequestbill/index";
};

// 页面加载时获取路由参数
onLoad((options) => {
  if (options?.id) {
    Id.value = options.id;
  } else {
    uni.showToast({
      title: "缺少ID参数",
      icon: "none",
    });
  }

  // 设置微信小程序分享功能
  // #ifdef MP-WEIXIN
  onShareAppMessage(() => {
    return {
      title: getShareTitle(),
      path: getSharePath(),
      imageUrl: "", // 可以设置分享图片
    };
  });
  // #endif
});

// 页面挂载后加载数据
onMounted(async () => {
  // 先加载选项数据
  await initializeOptions();

  if (Id.value) {
    const result = await loadInterviewDetail(Id.value);
    if (!result.success) {
      hasError.value = true;
    } else {
      // 设置审核权限标识
      isMyApprove.value = result.isMyApprove || false;

      // 加载招聘发布单详细信息
      await loadRecruitPublishInfo();

      // 加载成功后，获取时间线数据
      await getTimelineData();
    }
  }
});
</script>

<style lang="scss" scoped>
/* 主要内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20rpx;
  overflow-y: auto;
  min-height: calc(100vh - 80px);

  &.has-audit-actions {
    padding-bottom: 120rpx; // 为审核操作组件预留空间
  }
}

/* 标签按钮网格 */
.tab-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 16rpx;
  padding: 32rpx 24rpx;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 32rpx;
  margin-bottom: 24rpx;
}

.tab-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 16rpx 6rpx;
  border-radius: 20rpx;
  background: rgba(255, 255, 255, 0.15);
  border: 2rpx solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(8px);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  user-select: none;

  &.active {
    background: rgba(255, 255, 255, 0.9);
    border-color: rgba(255, 255, 255, 0.6);
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
    transform: translateY(-4rpx);

    .tab-label {
      color: #333;
      font-weight: 600;
    }
  }

  &:active {
    transform: scale(0.95) translateY(-2rpx);
  }

  .tab-label {
    color: rgba(255, 255, 255, 0.9);
    font-size: 24rpx;
    font-weight: 500;
    text-align: center;
    line-height: 1.2;
    transition: all 0.3s ease;
  }
}

/* 标签内容区域 */
.tab-content-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tab-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 详情卡片样式 */
.details-card {
  background: #ffffff;
  border-radius: 32rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2);
  overflow: hidden;
  margin-bottom: 24rpx;
  flex: 1;
  display: flex;
  flex-direction: column;

  .card-content {
    flex: 1;
    padding: 48rpx;
    overflow-y: auto;
  }
}

/* 子表卡片样式 */
.subtable-card {
  background: #ffffff;
  border-radius: 32rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2);
  overflow: hidden;
  margin-bottom: 24rpx;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 400rpx;
}

.card-header {
  background: #ffffff;
  padding: 40rpx 48rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.card-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 8rpx;
}

.card-subtitle {
  font-size: 28rpx;
  color: #666;
  display: block;
}

.card-content {
  flex: 1;
  padding: 48rpx;
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 1200rpx) {
  .tab-grid {
    gap: 12rpx;
    padding: 24rpx 16rpx;
  }

  .tab-button {
    padding: 16rpx 8rpx;

    .tab-label {
      font-size: 22rpx;
    }
  }

  .subtable-card {
    min-height: 350rpx;
  }

  .card-header {
    padding: 32rpx 36rpx;
  }

  .card-title {
    font-size: 32rpx;
  }

  .card-subtitle {
    font-size: 26rpx;
  }

  .card-content {
    padding: 36rpx;
  }
}

/* 超小屏幕优化 */
@media (max-width: 600rpx) {
  .tab-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 8rpx;
  }

  .tab-button {
    padding: 12rpx 6rpx;

    .tab-label {
      font-size: 20rpx;
    }
  }

  .subtable-card {
    min-height: 300rpx;
  }

  .card-header {
    padding: 28rpx 32rpx;
  }

  .card-title {
    font-size: 30rpx;
  }

  .card-subtitle {
    font-size: 24rpx;
  }

  .card-content {
    padding: 32rpx;
  }
}
</style>
